//
//  JCLEmoticonInputView.swift
//  表情键盘
//
//  Created by DDC on 2017/9/27.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

fileprivate let cellId  = "cellId"
class JCLEmoticonInputView: UIView {

    // collectionView
    @IBOutlet weak var collectionView: UICollectionView!
    // pageControl
    @IBOutlet weak var pageControl: UIPageControl!
    // toolbar
    @IBOutlet weak var toolbar: JCLToolbar!
    // 定义闭包属性
    fileprivate var selectedEmoticonCallBack:((_ emoticon:JCLEmoticon?)->())?
    // 加载自定义inputView的类方法
    // 添加闭包设置回调
    class func inputView(selectedEmoticonBlock:@escaping (_ emoticon:JCLEmoticon?)->()) -> JCLEmoticonInputView {
        let nib = UINib(nibName: "JCLEmoticonInputView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! JCLEmoticonInputView
        v.selectedEmoticonCallBack = selectedEmoticonBlock
        return v
    }
    
    // 注册collectionView
    override func awakeFromNib() {
        // 注册nib
        collectionView.register(JCLEmoticonCell.self, forCellWithReuseIdentifier: cellId)
        // 翻页动画
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        // 设置toolbar代理
        toolbar.delegate = self
        
        // 自定义pageControl图片显示
        guard let normalImage = UIImage(named: "compose_keyboard_dot_normal"),
            let selectedImage = UIImage(named: "compose_keyboard_dot_selected") else {
                return
        }
        // 利用KVC来赋值私有属性
        pageControl.setValue(normalImage, forKey: "_pageImage")
        pageControl.setValue(selectedImage, forKey: "_currentPageImage")
    }
}

// MARK:  - JCLToolbarDelegate
extension JCLEmoticonInputView:JCLToolbarDelegate {
    func jcl_toolbarDelegateSelectedIndex(toolbar: JCLToolbar, index: Int) {
        
        // 点击按钮实现collection联动
        let indexPath = IndexPath(item: 0, section: index)
        // collection滚动
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        // 将所选按钮的索引赋值给toolbar的属性，用于记录点击时的选中状态
        toolbar.selectedIndex = index
    }
}
// MARK: - UICollectionViewDataSource
extension JCLEmoticonInputView:UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return JCLEmoticonsManager.shared.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return JCLEmoticonsManager.shared.packages[section].numberOfPages
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! JCLEmoticonCell
        cell.emoticons = JCLEmoticonsManager.shared.packages[indexPath.section].emotions(page: indexPath.item)
        cell.delegate = self
        return cell
    }
  
    
}
// MARK: - UICollectionViewDelegate
extension JCLEmoticonInputView:UICollectionViewDelegate{
    /// collectionView滚动
    ///
    /// - Parameter scrollView: 滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        // 滚动到的目标分组属性
        var targetIndexPath:IndexPath?
        // 遍历所选分组的所有IndexPath
        let paths = collectionView.indexPathsForVisibleItems
        for indexPath in paths {
            
            // 判断中心点是否在当前cell的分组section中
            let cell = collectionView.cellForItem(at: indexPath)
            if cell?.frame.contains(center) == true {
                targetIndexPath = indexPath
                break
            }
        }
        guard let target = targetIndexPath else {
            return
        }
        // 将目标分组赋值给toolbar用户联动显示
        toolbar.selectedIndex = target.section
        
        // 设置pageControl
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item
    }
    
}
// MARK: - 遵循代理协议方法
extension JCLEmoticonInputView :JCLEmoticonCellDelegate {
    
    func emoticonCellDidSelectedEmoticon(cell: JCLEmoticonCell, emo: JCLEmoticon?) {
        
       selectedEmoticonCallBack?(emo)
        guard let emo = emo else {
            return
        }
        // 添加最近表情模型
        JCLEmoticonsManager.shared.recentEmoticon(emo: emo)
        // 如果当前组为‘最近’一组，不参与点击排序方法
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0 {
            return
        }
        
        // 刷新当前cell
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    
    }
}
